package cn.wmingming.e3mall.cart.interceptor;

import cn.wmingming.common.pojo.E3Result;
import cn.wmingming.common.utils.CookieUtils;
import cn.wmingming.e3mall.pojo.TbUser;
import cn.wmingming.e3mall.sso.service.UserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


/**
 * 判断用户是否登录，若登录，将user信息放进request域中
 */
public class LoginInterceptor implements HandlerInterceptor {

    @Autowired
    private UserService userService;
    @Value("${COOKIES_TOKEN}")
    private String COOKIES_TOKEN;
    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
        //目标方法执行前执行
        //返回true，放行	false：拦截
        //1.从cookie中取token
        String token = CookieUtils.getCookieValue(httpServletRequest, COOKIES_TOKEN);
        //2.如果没有token，未登录状态，直接放行
        if (StringUtils.isBlank(token)){
            return true;
        }
        //3.取到token，需要调用sso系统的服务，根据token取用户信息
        E3Result result = userService.getUserByToken(token);
        if(result.getStatus() != 200){
            //4.没有取到用户信息。登录过期，直接放行。
            return true;
        }
        //5.取到用户信息。登录状态。
        TbUser user = (TbUser) result.getData();
        //6.把用户信息放到request中。只需要在Controller中判断request中是否包含user信息。放行
        httpServletRequest.setAttribute("user",user);
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
        //目标方法执行后，返回ModelAndView前执行
    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
        //返回ModelAndView后执行
        //进行异常处理
    }
}
